var gulp = require('gulp');
var gutil = require('gulp-util');
var fs = require('fs');
var runSequence = require('run-sequence');
var include = require('gulp-file-include');
var minifycss = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var stripDebug = require('gulp-strip-debug');
var rename = require('gulp-rename');
var del = require('del');
var less = require('gulp-less');
var path = require('path');
var livereload = require('gulp-livereload');
var htmlmin = require('gulp-htmlmin');
var mainBower = require('gulp-main-bower-files');
var filter = require('gulp-filter');
var concat = require('gulp-concat');


// ************************************* 常量 ******************************************

var SRC = {
	src: './src',
	js: './src/js',
	less: './src/less',
	images: './src/images',
	fonts: './src/fonts',
	mock: './src/mock',
	html: './src/html',
	components: './src/components',
	libs: 'bower_components'
};

var DIST = {
	dist: './dist',
	css: './dist/css',
	js: './dist/js',
	libs: './dist/libs',
	images: './dist/images',
	fonts: './dist/fonts',
	mock: './dist/mock',
	components: './dist/components'
};

var FILES = {
	less: '/*.less',
	css: '/**/*.css',
	js: '/**/*.js',
	images: '/**',
	fonts: '/**',
	mock: '/**',
	html: '/*.html',
	components: '/**'
};


// 获取目录列表
function getFolders(dir) {
	return fs.readdirSync(dir)
		.filter(function(file) {
			return fs.statSync(path.join(dir, file)).isDirectory();
		});
}

// 创建初次使用的目录
function initFolders() {
	var fdLst = [DIST.dist, SRC.src, SRC.html, SRC.less, SRC.js, SRC.fonts, SRC.images, SRC.mock, SRC.components];
	return fdLst.map(function(folder) {
		if (!fs.existsSync(folder)) {
			fs.mkdirSync(folder);
		}
	});
}

// ************************************* 编译及压缩 *************************************
// 清理缓存文件
gulp.task('clean', function(cb) {
	return del([DIST.dist + FILES.html, DIST.css + FILES.css, DIST.js + FILES.js, DIST.images + FILES.images, DIST.mock + FILES.mock, DIST.components + FILES.components], {force: true}, cb);
});

// 编译less用于调试
gulp.task('css', ['clean'], function() {
	// 编译less并存到css目录
    return gulp.src(SRC.less + FILES.less)
		.pipe(less({
			paths: [path.join(__dirname, 'less', 'includes')]
		}))
		.pipe(gutil.env.type === 'production' ? minifycss() : gutil.noop())
		.pipe(gulp.dest(DIST.css));
});

// 压缩js
gulp.task('js', ['clean'], function() {
	return gulp.src(SRC.js + FILES.js)
		.pipe(gutil.env.type === 'production' ? stripDebug() : gutil.noop())
		.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
		// .pipe(rename({suffix: '.min'}))
		.pipe(gulp.dest(DIST.js))
		.pipe(gutil.env.type === 'production' ? gutil.noop() : livereload());
});

// 复制html并压缩
gulp.task('html', ['clean'], function() {
	return gulp.src(SRC.html + FILES.html)
		.pipe(include({
			prefix: '@@',
			basepath: '@file'
		}))
		.pipe(gutil.env.type === 'production' ? htmlmin({collapseWhitespace: true}) : gutil.noop())
		.pipe(gulp.dest(DIST.dist))
		.pipe(gutil.env.type === 'production' ? gutil.noop() : livereload());
});

// 第三方库
gulp.task('libs', ['clean'], function() {
	var folders = getFolders(SRC.libs);
	var tasks = folders.map(function(folder) {
		var dst = SRC.libs + '/' + folder + '/dist';
		if (!fs.existsSync(dst)) dst = SRC.libs + '/' + folder + '/dest';
		if (!fs.existsSync(dst)) dst = SRC.libs + '/' + folder + '/player';
		return gulp.src(dst + '/**/*')
			.pipe(gulp.dest(DIST.libs + '/' + folder));
	});
});

// 组件库
gulp.task('components', ['clean'], function() {
	return gulp.src(SRC.components + FILES.components)
		.pipe(gulp.dest(DIST.components));
});

// bower
gulp.task('main-bower', ['clean'], function() {
	var filterJS = filter('**/*.js', {restore: true});
	return gulp.src('./bower.json')
		.pipe(mainBower({
			overrides: {}
		}))
		.pipe(filterJS)
		.pipe(uglify())
		.pipe(filterJS.restore)
		.pipe(gulp.dest(DIST.libs));
});

// 资源
gulp.task('images', ['clean'], function() {
	return gulp.src(SRC.images + FILES.images)
		.pipe(gulp.dest(DIST.images));
});

gulp.task('fonts', ['clean'], function() {
	return gulp.src(SRC.fonts + FILES.fonts)
		.pipe(gulp.dest(DIST.fonts));
});

gulp.task('mock', ['clean'], function() {
	return gulp.src(SRC.mock + FILES.mock)
		.pipe(gulp.dest(DIST.mock));
});

gulp.task('res', ['images', 'fonts', 'mock']);

// ************************************* 发布 *************************************
gulp.task('init-all', function(cb) {
	initFolders();
	console.log('PROJECT INITED SUCCESSFULLY');
});

gulp.task('build', ['html', 'css', 'js', 'main-bower', 'components', 'res']);

gulp.task('default', ['html', 'css', 'js', 'main-bower', 'components', 'res']);

gulp.task('build-dev', function(cb) {
	gutil.env.type = 'debug';
	runSequence(
		'build',
		function(err) {
			if (err) {
				console.log(err.message);
			}
			else {
				console.log('DEBUG FINISHED SUCCESSFULLY');
			}
		}
	);
});

gulp.task('build-release', function(cb) {
	gutil.env.type = 'production';
	runSequence(
		'build',
		function(err) {
			if (err) {
				console.log(err.message);
			}
			else {
				console.log('RELEASE FINISHED SUCCESSFULLY');
			}
		}
	);
});

// 监控文件变化，自动编译
gulp.task('watch', function() {
	livereload.listen();
	gulp.watch(SRC.less + FILES.less, ['css']);
	gulp.watch(SRC.js + FILES.js, ['js']);
	gulp.watch(SRC.mock + FILES.mock, ['mock']);
	gulp.watch(SRC.html + FILES.html, ['html']);
	console.log('watching...');
});